<?php
/**
 * 抽奖小程序用户相关接口
 * 作者：刘单风
 * 最后修改时间：2018-11-14
 * 版权：医库PHP小组
 */
namespace app\api\controller;
use app\model\Users;
use think\facade\Config;
use MoCommon\WeChat\Wx;
use MoCommon\WeChat\WXBizDataCrypt;
use MoCommon\Support\Codes;
use MoCommon\Support\Helper;
use think\facade\Cache;
use think\facade\Log;
use think\facade\Env;

class Account extends Apibase
{
    /**
     * 小程序登录
     */
    public function splogin()
    {
        $wechat = Config::get('app.wechat');
        $appid = $wechat['appid'];
        $secret = $wechat['secret'];

        $code = input('code');
        //微信user_info 返回的加密数据( encryptedData )
        $encryptedData = input('encryptedData');

        //微信user_info 返回的初始向量 iv
        $iv = input('iv');
        $session = Wx::jscode_to_session($appid, $secret, $code);
        $return_data = [];
        $status = Codes::ACTION_FAL;

        if (!$session['session_key']) {
            $message = '小程序session_key获取错误';
        } else {
            $errCode = 0;
            if ($encryptedData) {
                $pc = new WXBizDataCrypt($appid, $session['session_key']);
                $errCode = $pc->decryptData($encryptedData, $iv, $data);
            }
            if ($errCode == 0) {
                $Users=new Users();
                $userinfo = $data ? json_decode($data, true) : [];
                $member = $Users->findOne(["openid" => $session['openid']]);
                $data = [
                    'nick_name' => urlencode($userinfo['nickName']) ?: '',
                    'head_img' => $userinfo['avatarUrl'] ?: '',
                    'openid' => $session['openid'],
                    'login_time' => $_SERVER['REQUEST_TIME'],
                    'create_time' => $_SERVER['REQUEST_TIME']
                ];
                if (empty($member['openid'])) {
                    //没有此用户新增
                    $uid = $Users->addOne($data);
                    $member = $Users->findOne(["id" => $uid]);
                }
//                else if (empty($member['unionid'])) {
//                    $Users->updateOne($member['id'], [
//                        'unionid' => $session['unionid'] ?: '222'
//                    ]);
//                }

                if ($member['nick_name'] != $data['nick_name'] || $member['head_img'] != $data['head_img']) {
                    //更新头像和昵称
                    $Users->updateOne($member['id'], [
                        'nick_name' => $data['nick_name'],
                        'head_img' => $data['head_img']
                    ]);
                }


                $data['id'] = $member['id'];
                $data['session_key'] = $session['session_key'];
                $user_id = $member['id'];

                // 给用户生成token
                $sign = Helper::gentoken($user_id);

                //存入redis
                $options=Config::get('app.converse');
                $redis = Cache::init($options);
                $redis->set($sign, json_encode($data), $options['expire']);

                $member['nick_name']=urldecode($member['nick_name']);
                $return_data['sign'] = $sign;
                $return_data['user_info'] = $member;
                $status = Codes::ACTION_SUC;
                $message = Codes::get(Codes::ACTION_SUC);

            } else {
                Log::init([
                    'type' => 'File',
                    'path' => Env::get("root_path") . 'public/logs/'
                ]);
                Log::error(json_encode($errCode));
                Log::error(json_encode($data));
                $message = '小程序用户信息错误';
            }

        }
        return parent::respond($return_data,$status,$message);
    }

    /**
     * 获取用户信息
     */
    public function userinfo()
    {
        $userid = $this->getUid();
        $userinfo = Users::findOne(['id' => $userid]);
        return parent::respond($userinfo);
    }
}